<?php
global $Config;
require_once($Config->WebCMSRoot.'Base/Model.php');
//require_once($Config->WebCMSRoot.'Data/Form.php');

Class MailFormModel extends BaseModel
{
    var $To;
    var $From;
    var $Subject;
	var $Template;
    var $Content;
    var $MultipleRecipients;
	
	var $__headers;
	var $__template;
    var $__bodyText;
    var $__bodyHTML;
    var $__body;
	var $__mimeBoundary;
    var $__attachments;

	function MailFormModel($to, $from, $subject, $template, $content=array(), $multipleRecipients=false)
	{
		$this->To                 = $to;
		$this->From               = $from;
		$this->Subject            = $subject;
		$this->Template           = $template;
		$this->Content            = $content;
		$this->MultipleRecipients = $multipleRecipients;
		
		$this->__headers      = '';
		$this->__template     = '';
	    $this->__bodyText     = '';
	    $this->__bodyHTML     = '';
	    $this->__body         = '';
		$this->__mimeBoundary = md5(uniqid(rand(), true));
	    $this->__attachments  = array();

        parent::BaseModel();
	}

    function Send()
    {
      $this->__buildMail();
      $this->__body  = '';
      $this->__body .= $this->__bodyHTML;
      $this->__body .= $this->__bodyText;
      
      if ($this->MultipleRecipients)
      {
        $to = '';
        foreach ($this->To as $key=>$email)
        {
          $to = $this->__formatRecipient($email[0], $email[1]) . ', ';
        }
        $to = substr($to, -2);
        
        if(mail($to,$this->Subject,$this->__body, $this->__headers))
        {
          return true;
        }
        else
        {
          return false;
        }
      }
      else
      {
//print('<pre>'.var_export($this,true).'</pre>');exit;
        $retval = true;
        foreach ($this->To as $key=>$email)
        {
          $to = $this->__formatRecipient($email[0], $email[1]);
//print('<pre>'.var_export($to,true).'</pre>');//exit;
//print('<pre>'.var_export($this->__body,true).'</pre>');//exit;

          if(!mail($to, $this->Subject, $this->__body, $this->__headers))
          {
            $retval = false;
          }
        }
//print('<pre>'.var_export($retval,true).'</pre>');//exit;
        return($retval);
      }
    }
    
    /* Internal Functions */
  
    function __buildMail()
    {
      $this->__setHeaders();
      $this->__setBody();
      $this->__addAttachments();
    }
    
    function __setHeaders()
    {
		$this->From[1] = count($this->From) == 1 ? '' : $this->From[1];
		
		$this->__headers  = "From: ".$this->__formatRecipient($this->From[0], $this->From[1], False)."  \r\n";
		$this->__headers .= "Reply-To: ".$this->__formatRecipient($this->From[0], $this->From[1], False)." \r\n";
		$this->__headers .= "MIME-Version: 1.0\r\n";
		$this->__headers .= "Content-Type: multipart/alternative; boundary=".$this->__mimeBoundary."\n";
		$this->__headers .= "X-Sender: ".$this->__formatRecipient($this->From[0], $this->From[1], False)."\n";
		$this->__headers .= "X-Mailer: Anthoro.Mail - PHP4\n";
		$this->__headers .= "X-Priority: 3\n";
		$this->__headers .= "Return-Path: <".$this->From[0].">\n";
		$this->__headers .= "This is a multi-part message in MIME format.\n";
    }
    
    function __setBody()
    {
      if ($this->Template != '')
      {
		global $Config;
		
		$textFile = $Config->SiteRoot.'templates/'.$this->Template.'.txt';
		$htmlFile = $Config->SiteRoot.'templates/'.$this->Template.'.html';
		
		// Text
		if (file_exists($textFile))
		{
	        $str = file_get_contents($textFile);
	        $str = $this->__mergeTemplate($str);
	        $this->__setTextBody($str);
		}
		
		// HTML
		if (file_exists($htmlFile))
		{
	        $str = file_get_contents($htmlFile);
	        $str = $this->__mergeTemplate($str);
	        $this->__setHTMLBody($str);
		}
      }
    }
    
    function __setHTMLBody($bodyHTML)
    {
      if ($bodyHTML != '')
      {
// TODO: use regex
        $bodyHTML = str_replace('=', '=3D', $bodyHTML);
        $bodyHTML = str_replace('=3D3D', '=3D', $bodyHTML);
        $bodyHTML = str_replace('&#40;', '(', $bodyHTML);
        $bodyHTML = str_replace('&#41;', ')', $bodyHTML);

        $body_str  = "--" . $this->__mimeBoundary . "\n";
        $body_str .= "Content-Type: text/html; charset=UTF-8\n";
        $body_str .= "Content-Transfer-Encoding: quoted-printable\n";
        $body_str .= "\n\n";
        $body_str .= $bodyHTML;
        $body_str .= "\n\n";
  
        $this->__bodyHTML = $body_str;
      }
    }
    
    function __setTextBody($bodyText)
    {
      if ($bodyText != '')
      {
// TODO: use regex
        $bodyText = str_replace('=', '=3D', $bodyText);
        $bodyText = str_replace('=3D3D', '=3D', $bodyText);
        $bodyText = str_replace('&#40;', '(', $bodyText);
        $bodyText = str_replace('&#41;', ')', $bodyText);

        $body_str  = "--" . $this->__mimeBoundary . "\n";
        $body_str .= "Content-Type: text/plain; charset=UTF-8\n";
        $body_str .= "Content-Transfer-Encoding: quoted-printable\n";
        $body_str .= "\n\n";
        $body_str .= $bodyText;
        $body_str .= "\n\n";
        
        $this->__bodyText = $body_str;
      }
    }
    
    function __addAttachments()
    {
      if(count($this->__attachments) > 0)
      {
        $this->__body  = implode($this->__attachments);
        $this->__body .= "--MIME_BOUNDRY--\n";
      }
    }
    
    function __mergeTemplate($template)
    {
// TODO: use regex
//print('<pre>'.var_export($this->Content,true).'</pre>');exit;
      foreach($this->Content as $key=>$content)
      {
        $template = str_replace("[$key]", $content, $template);
      }
      
      return $template;
    }

    function __setFileSection($file)
    {
      if($str = file_get_contents($file))
      {
        $str = file_get_contents($file);
        $bname = basename($file);
        $str = chunk_split(base64_encode($str));
        $section .= "--MIME_BOUNDRY\n";
        $section .= "Content-Type: ".$this->determine_mime($file)."; name=\"$bname\"\n";
        $section .= "Content-disposition: attachment\n";
        $section .= "Content-Transfer-Encoding: base64";
        $section .= "\n\n";
        $section .= $str;
        $section .= "\n\n";
        return $section;
      }
      else
      {
        $problem = "";
        if(!file_exists($file))
        {
          $problem = "File could not be found";
        }
        echo("<strong>unable to load specified file $file_path in set_file_section method</strong> <br>$problem");
        exit();
      }
    }

    function __determineMime($name)
    {
      $str = basename($name);
      $name_arr = explode(".",$str);
      $len = count($name_arr) - 1;
      $name_arr[$len] = strtolower($name_arr[$len]);
      
      switch($name_arr[$len])
      {
        case "jpg":
          $type = "image/jpeg";
          break;
        case "jpeg":
          $type = "image/jpeg";
          break;
        case "gif":
          $type = "image/gif";
          break;
        case "txt":
          $type = "text/plain";
          break;
        case "pdf":
          $type = "application/pdf";
          break;
        case "csv";
          $type = "text/csv";
          break;
        case "html":
          $type = "text/html";
          break;
        case "htm":
          $type = "text/html";
          break;
        case "xml":
          $type = "text/xml";
          break;
      }
      
      return $type;
    }
    
    function __formatRecipient($email, $name, $useEmailOnly=True)
    {
      if ($name == '' || $useEmailOnly)
      {
        $to = "$email";
      }
      else
      {
        $to = "$name <$email>";
      }
      
      return $to;
    }
}
?>